package com.example.demo.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.util.StringUtils;
import com.example.demo.mapper.BlobImageMapper;
import com.example.demo.service.BlobService;
import com.example.demo.utils.ImageMergeUtil;
import com.example.demo.vo.BlobImageBase64;
import com.example.demo.vo.BlobVo;
import com.example.demo.vo.CensusImageVo;
import com.example.demo.vo.ImageVo;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BlobServiceImpl implements BlobService {

    @Autowired
    private BlobImageMapper blobImageMapper;

    @Override
    public List<BlobVo> getImage() {
        List<BlobVo> imageList = blobImageMapper.getImage();


        for (BlobVo blobVo : imageList) {
            if (blobVo.getImage() != null && !blobVo.getImage().isEmpty()) {
                try {
                    // 1. 提取纯 Base64 数据（如果包含前缀）
                    String base64Data = blobVo.getImage();
                    if (base64Data.contains(",")) {
                        base64Data = base64Data.split(",")[1];
                    }

                    // 2. 解码 Base64 为字节数组
                    byte[] imageBytes = Base64.decodeBase64(base64Data);

                    // 3. 设置到 BlobVo 中
                    blobVo.setImageData(imageBytes);

                } catch (Exception e) {
                    blobVo.setImageData(null);
                }
            } else {
                blobVo.setImageData(null);
            }
        }

        return imageList;
    }


    public List<ImageVo> getAllImage() {
        List<ImageVo> imageId = blobImageMapper.getImageId();
        List<ImageVo> result = new ArrayList<>();
        for (ImageVo imageVo : imageId) {
            for (String id : imageVo.getImageId().split(",")) {
                ImageVo imageVo1 = new ImageVo();
                BeanUtil.copyProperties(imageVo, imageVo1);
                imageVo1.setCensusImageId(id);
                result.add(imageVo1);
            }
        }

        return result;
    }


//    public List<CensusImageVo> censusImage() {
//        List<CensusImageVo> allCensusTasks = blobImageMapper.getAllCensusTasks();
//        List<CensusImageVo> imageList = new ArrayList<>();
//        //存id
//        List<ImageVo> result = new ArrayList<>();
//        for (CensusImageVo allCensusTask : allCensusTasks) {
//            for (String id : allCensusTask.getImageIds().split(",")) {
//                ImageVo imageId = new ImageVo();
//                BeanUtil.copyProperties(allCensusTask,imageId);
//                imageId.setCensusImageId(id);
//                CensusImageVo censusImage = blobImageMapper.getCensusImage(imageId);
//                imageList.add(censusImage);
//            }
//        }
////        for (CensusImageVo allCensusTask : allCensusTasks) {
////            ImageVo imageVo = new ImageVo();
////            imageVo.setImageId(allCensusTask.getImageIds());
////            CensusImageVo censusImage = blobImageMapper.getCensusImage(imageVo);
////            imageList.add(censusImage);
////        }
//        for (CensusImageVo allCensusTask : allCensusTasks) {
//            for (CensusImageVo censusImageVo : imageList) {
//                if (allCensusTask.getImageIds().equals(censusImageVo.getImageIds())) {
//                    allCensusTask.setImage(censusImageVo.getImage());
//                    if (allCensusTask.getImage() != null && !allCensusTask.getImage().isEmpty()) {
//                        try {
//                            String base64Data = allCensusTask.getImage();
//                            if (base64Data.contains(",")) {
//                                base64Data = base64Data.split(",")[1];
//                            }
//                            byte[] imageBytes = Base64.decodeBase64(base64Data);
//                            allCensusTask.setImageData(imageBytes);
//
//                        } catch (Exception e) {
//                            allCensusTask.setImage(null);
//                        }
//                    }else{
//                        allCensusTask.setImageData(null);
//                }
//            }
//        }
//    }
//
//
//        return allCensusTasks;
//}


    public List<CensusImageVo> censusImage() {
        // 1. 获取所有任务数据
        List<CensusImageVo> allTasks = blobImageMapper.getAllCensusTasks();

        // 2. 批量收集所有图片ID
        Map<Integer, List<String>> taskImagesMap = new HashMap<>();
        List<Integer> allImageIds = new ArrayList<>();

        for (CensusImageVo task : allTasks) {
            if (task.getImageIds() != null && !task.getImageIds().isEmpty()) {
                List<String> ids = Arrays.asList(task.getImageIds().split(","));
                taskImagesMap.put(task.getId(), ids);

                // 将字符串ID转换为整数ID
                for (String id : ids) {
                    try {
                        allImageIds.add(Integer.parseInt(id.trim()));
                    } catch (NumberFormatException e) {
                        System.out.println("12");
                    }
                }
            }
        }

        // 3. 批量查询所有图片Base64 - 修复类型问题
        Map<Integer, String> imageDataMap = new HashMap<>();
        if (!allImageIds.isEmpty()) {
            // 使用显式类型声明解决类型推断问题
            List<BlobImageBase64> base64List = blobImageMapper.getBase64ImagesByIds(allImageIds);

            // 使用显式转换解决类型问题
            imageDataMap = base64List.stream()
                    .collect(Collectors.toMap(
                            item -> item.getId(),          // 显式lambda表达式
                            item -> item.getImageBase64()  // 显式lambda表达式
                    ));
        }

        // 4. 为每个任务设置图片列表并合并
        for (CensusImageVo task : allTasks) {
            List<String> imageIds = taskImagesMap.get(task.getId());
            if (imageIds != null && !imageIds.isEmpty()) {
                List<String> base64List = new ArrayList<>();

                for (String idStr : imageIds) {
                    try {
                        int id = Integer.parseInt(idStr.trim());
                        String base64 = imageDataMap.get(id);
                        if (base64 != null) {
                            base64List.add(base64);
                        }
                    } catch (NumberFormatException e) {
                        System.out.println("1212");
                    }
                }

                if (!base64List.isEmpty()) {
                    try {
                        byte[] mergedImage = ImageMergeUtil.mergeImages(base64List);
                        task.setImageData(mergedImage);
                    } catch (Exception e) {
                        System.out.println("123");
                        task.setImageData(null);
                    }
                }
            }
        }

        return allTasks;
    }


//多个导出
//    @Override
//    public List<CensusTaskExportVo> exportCensusTasks() {
//        // 1. 获取所有任务数据
//        List<CensusTaskExportVo> taskList = blobImageMapper.getAllCensusTasks();
//
//        // 2. 收集所有图片ID（去重）
//        Set<Integer> allImageIds = new HashSet<>();
//        for (CensusTaskExportVo task : taskList) {
//            if (StringUtils.isNotBlank(task.getImageIds())) {
//                Arrays.stream(task.getImageIds().split(","))
//                        .map(String::trim)
//                        .filter(StringUtils::isNumeric)
//                        .map(Integer::parseInt)
//                        .forEach(allImageIds::add);
//            }
//        }
//
//        // 3. 批量查询所有关联图片的Base64数据
//        Map<Integer, String> imageBase64Map = Collections.emptyMap();
//        if (!allImageIds.isEmpty()) {
//            imageBase64Map = blobImageMapper.getBase64ImagesByIds(new ArrayList<>(allImageIds))
//                    .stream()
//                    .collect(Collectors.toMap(
//                            image -> image.getImageId(),
//                            image -> image.getImage(),
//                            (existing, replacement) -> existing // 如果有重复ID，保留第一个
//                    ));
//        }
//
//        // 4. 处理每个任务的图片数据
//        for (CensusTaskExportVo task : taskList) {
//            List<String> base64List = new ArrayList<>();
//            List<byte[]> imageBytesList = new ArrayList<>();
//
//            if (StringUtils.isNotBlank(task.getImageIds())) {
//                // 解析图片ID列表
//                List<Integer> imageIds = Arrays.stream(task.getImageIds().split(","))
//                        .map(String::trim)
//                        .filter(StringUtils::isNumeric)
//                        .map(Integer::parseInt)
//                        .collect(Collectors.toList());
//
//                // 收集Base64数据并解码
//                for (Integer imageId : imageIds) {
//                    String base64 = imageBase64Map.get(imageId);
//                    if (base64 != null && !base64.isEmpty()) {
//                        base64List.add(base64);
//
//                        try {
//                            String pureBase64 = base64.contains(",")
//                                    ? base64.split(",")[1]
//                                    : base64;
//
//                            imageBytesList.add(Base64.decodeBase64(pureBase64));
//                        } catch (Exception e) {
//                            // 记录错误但继续处理其他图片
//                            // log.error("Base64解码失败: imageId={}", imageId, e);
//                        }
//                    }
//                }
//            }
//
//            task.setImageBase64List(base64List);
//            task.setImageData(imageBytesList);
//        }
//
//        return taskList;
//    }

}